import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { message } from 'antd';
import myStyle from './style.less';
import ChangeModalC from './changeModalC';
import { PrimaryC, DATA_ENTRY, AdvancedSearch, TableC, FirstHeaderC, ContentPackage } from '../../../comps';
import { formSelectData } from '../../../utils/utils';

@connect(({ accountNumberM, globalM, loading }) => ({
  accountNumberM,
  globalM,
  loading: loading.effects['accountNumberM/getAccountData'],
}))
export default class AccountNumberManageC extends PureComponent {
  state = {
    isReset: false, //判断是否点击重置
    isEdit: false, //默认为新增（编辑：true,新增：false
    visible: false, //模态框显示/隐藏
    columns: [],
    dataSource: [], //存款账号数据
    total: 0,
    currentPage: 1, //页码
    numInPage: 10, //每页条数
    searchObj: {}, //查询条件
    editObj: {}, //编辑信息
    accountTypeList: [], //存款类型下拉列表
    productCode: '',
  };
  componentDidMount() {
    const {
      globalM: {
        dataDictionary: { CKLX = [] },
      },
    } = this.props;
    // 获取存款类型下拉列表
    this.setState({
      accountTypeList: formSelectData(CKLX),
    });
    // 获取存款账号信息
    this.getTableData();
  }
  // 获取存款账号信息
  getTableData = () => {
    const { searchObj, currentPage, numInPage } = this.state;
    this.props.dispatch({
      type: 'accountNumberM/getAccountData',
      payload: {
        ...searchObj,
        currentPage: currentPage,
        numInPage: numInPage,
      },
      callback: (type, data) => {
        if (type == 'success') {
          data.columns &&
            data.columns.length &&
            data.columns.forEach((item) => {
              if (item.dataIndex == 'accountType') {
                // 存款类型前端翻译
                item.render = (text, record, index) => {
                  if (text === null || text === undefined) {
                    return '--';
                  } else {
                    if (isNaN(text)) {
                      return text;
                    } else {
                      let temp = this.state.accountTypeList?.length && this.state.accountTypeList.find((item) => item.value == text);
                      return temp ? temp.title : text;
                    }
                  }
                };
              }
            });
          this.setState({
            columns: data.columns,
            dataSource: data.dataSource,
            total: data.pageInfo.total,
          });
        }
      },
    });
  };
  //编辑存款账号
  editAccount = (record) => {
    // let tempObj = {}
    // for (let key in record) {
    //     if (key == 'accountType') {
    //         tempObj[key] = record[key] == '活期存款' ? '1' : '0'
    //     } else {
    //         tempObj[key] = record[key]
    //     }
    // }
    this.setState({
      visible: true,
      isEdit: true,
      editObj: record,
    });
  };
  // 删除存款账号
  deleteAccount = (record) => {
    this.props.dispatch({
      type: 'accountNumberM/deleteAccountById',
      payload: {
        id: record.id,
      },
      callback: (type) => {
        if (type == 'success') {
          this.getTableData();
        }
      },
    });
  };
  //表格页码排序改变调用
  handleTableChange = (pagination) => {
    const { current, pageSize } = pagination;
    const { isReset } = this.state;
    if (isReset) {
      //判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      this,
        this.setState({
          isReset: false,
        });
      return;
    }
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
      },
      () => {
        this.getTableData();
      },
    );
  };
  // 显示存款账号信息表格
  showTable = () => {
    const { currentPage, total, numInPage, columns, dataSource } = this.state;
    //因为columns来自props，会不停的渲染添加操作列，在此做一下判断
    dataSource &&
      dataSource.forEach((value) => {
        if (value.rootPortfolioCode.indexOf(' ') == -1) {
          value.rootPortfolioCode = value.rootPortfolioCode + ' - ' + value.rootPortfolioName;
        }
      });
    if (columns && columns.length) {
      // 最后一列添加操作列
      if (columns[columns.length - 1].title != '操作') {
        columns.push({
          dataIndex: 'operate',
          key: 'operate',
          type: 'operate',
          title: '操作',
          width: '100px',
          // fixed: 'right',
          operates: [
            {
              title: '编辑',
              onClick: (record, index) => {
                this.editAccount(record);
              },
            },
            {
              title: '删除',
              onClick: (record, index) => {
                this.deleteAccount(record);
              },
            },
          ],
        });
      }
      columns.map((item) => {
        if (item.key == 'account' || item.key == 'rootPortfolioCode' || item.key == 'bankName' || item.key == 'accountName') {
          item.width = 200;
        }
        if (item.key == 'branchBankName') {
          item.width = 120;
        }
        if (item.key == 'accountType' || item.key == 'paymentNo' || item.key == 'startDate' || item.key == 'rate') {
          item.width = 90;
        }
      });
    }

    return (
      <TableC
        columns={columns}
        loading={this.props.loading}
        dataSource={dataSource}
        current={currentPage}
        total={total}
        pageSize={numInPage}
        rowKey='id'
        selfScrollY={true}
        pagination={true}
        scroll={{ x: 'max-content' }}
        onChange={this.handleTableChange}
      />
    );
  };
  // 改变visible
  changeVisible = (msg) => {
    this.setState({
      visible: msg,
    });
  };
  // 添加账号模态框打开
  addModalOpen = () => {
    this.setState({
      visible: true,
      isEdit: false,
    });
  };
  //查询表格数据
  queryTableList = (e) => {
    let tempQuery = {};
    for (let k in e) {
      if (k == 'productCode') {
        tempQuery.product = this.state.productCode;
      } else {
        tempQuery[k] = e[k];
      }
    }
    this.setState(
      {
        columns: [],
        dataSource: [],
        searchObj: tempQuery,
        currentPage: 1,
        numInPage: 10,
        isReset: false,
      },
      () => {
        this.getTableData();
      },
    ); //查询之前清除数据
  };
  //子组件调用父组件的getTableData方法
  useGetTableData = (msg) => {
    if (msg) {
      this.getTableData();
    }
  };
  render() {
    const { accountTypeList } = this.state;
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'productCode',
          title: '产品',
          type: DATA_ENTRY.PRODUCTLIST,
          onChange: (e) => {
            //取产品的code 传给后台
            if (!e) {
              this.setState({
                productCode: '',
              });
              return;
            }
            const arr = e.info.portfolioCode;
            this.setState({
              productCode: arr.length ? arr : '',
            });
          },
        },
        {
          dataIndex: 'headOffice',
          title: '存款总行',
          type: DATA_ENTRY.INPUT,
          allowClear: true,
        },
        {
          dataIndex: 'accountType',
          title: '存款类型',
          type: DATA_ENTRY.SELECT,
          dataSource: accountTypeList,
          allowClear: true,
        },
      ],
      //点击查询按钮
      onQuery: (e) => {
        this.queryTableList(e);
      },
      onClear: () => {
        //点击重置按钮
        this.setState({
          searchObj: {},
          isReset: true,
        });
      },
    };
    return (
      <ContentPackage
        title='存款账号管理'
        contentHtml={
          <div className={myStyle.accountNumber}>
            <div className={'cardBody'}>
              <AdvancedSearch {...searchProps} />
            </div>
            <div>
              <PrimaryC title='新增' style={{ margin: '10px' }} onClick={this.addModalOpen} />
              {this.state.visible ? (
                <ChangeModalC
                  useGetTableData={this.useGetTableData}
                  editObj={this.state.editObj}
                  visible={this.state.visible}
                  changeVisible={this.changeVisible}
                  isEdit={this.state.isEdit}
                  dataSource={this.state.dataSource}
                />
              ) : null}
            </div>
            <div>{this.showTable()}</div>
          </div>
        }
      />
    );
  }
}
